package W072_081.src.controller;

import W072_081.src.dao.SchoolService;
import W072_081.src.entity.School;
import W072_081.src.exception.BaseException;
import W072_081.src.factory.ServiceFactory;
import W072_081.src.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;

@WebServlet("/sc")
public class SchoolCreateCtrl extends HttpServlet {
    private SchoolService schoolService = ServiceFactory.getService(SchoolService.class,"SchoolService");
    public SchoolCreateCtrl() throws InvocationTargetException, BaseException {}
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String school_json= JSONUtil.getJSON(request);
        School schoolToadd= JSON.parseObject(school_json, School.class);
        response.setContentType("application/json;charset=utf-8");
        JSONObject message = new JSONObject();
        try {
            schoolService.add(schoolToadd);
            message.put("message","添加成功");
            message.put("code",200);
        }catch (SQLException e){
            message.put("message","添加失败");
            message.put("code",500);
        }catch (Exception e){
            message.put("message","网络异常");
            message.put("code",500);
        }
        response.getWriter().println(JSON.toJSONString(message));
    }
}
